<?php
	require_once "dBConnect.php";
	require_once 'Zend/Loader.php';
	require_once "commonfuncs.php";
	Zend_Loader::loadClass('Zend_Http_Client');
	Zend_Loader::loadClass('Zend_Http_Client_Adapter_Socket');
	Zend_Loader::loadClass('Zend_Gdata');
	Zend_Loader::loadClass('Zend_Gdata_AuthSub');
	//Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
	Zend_Loader::loadClass('Zend_Gdata_Calendar');
	//Zend_Loader::loadClass('Zend_Json');
	Zend_Loader::loadClass('Zend_Gdata_App_CaptchaRequiredException');
	
	//start our session; all object code must be above this line so the session knows how to recreate any objects that are stored in it
	session_start();
	
	//get the database object
	$db = new dBConnect();

	/*three cases to expect
	(1)The user has been redirected from Google so we need to use a username/password (stored in the session?) to associate to $_GET['token'] in the database; we must first exchange it for a session_token
	(2)The user provided an incorrect or nonexistent username and/or password
	(3)The user has registered but we did not get a token. In this case redirect to Google and fall back to case (1)
	*/
	if(isset($_GET['token'])){
		$token = Zend_Gdata_Authsub::getAuthSubSessionToken($_GET['token']);
		$table = "users";
		$data = "authsub='$token'";
		$conditions = "username='".$_SESSION['tmpusr']."' and password='".$_SESSION['tmpswrd']."'";
		if(!$db->update($table, $data, $conditions)){//if insert is unsuccessful return failure
			echo "could not insert token";return 0;
		}
	}else{
		$conditions = "username='".$_POST['username']."' and password='".$_POST['password']."'";
		$table = "users";
		$result = $db->getData("*", $table, $conditions); 
		if(!count($result)){
			echo "Incorrect username or password";
			return 0;//the search failed there is no matching username/password combination
		}else if(!$result[0]['authsub']){
			$_SESSION['tmpusr'] = $_POST['username'];
			$_SESSION['tmpswrd'] = $_POST['password'];
			$_SESSION['username'] = $_POST['username'];
			header("location:".getAuthSubUrl());
		}else {//all is okay we have a token to use to create the client ^_^
			$token = $result[0]['authsub'];
			$_SESSION['username'] = $_POST['username'];
		}
	}
	if($token){
		$_SESSION['client'] = Zend_Gdata_Authsub::getHttpClient($token);
		header("location:viewMonth.php");
		}
?>
